#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>

#define PATH "/home/"
#define PROJ_ID 9600

int main()
{
    //1.创建key
    key_t key = ftok(PATH, PROJ_ID);

    //2.创建共享内存
    int shmid = shmget(key, 1024, IPC_CREAT | 0777);
    if (shmid == -1)
    {
        perror("shmget erorr");
        return -1;
    }

    //3.映射
    int* data = shmat(shmid, NULL, 0);
    if (data == NULL)
    {
        perror("shmat error");
        return -1;
    }
    *data = 0;

    //创建子进程
    pid_t pid = fork();
    if (pid == 0)
    {
        int i = 100000;
        while (i--)
        {
            (*data)++;
            printf("child:%d\n", *data);
        }
        shmdt(data);//子进程解映射
        exit(0);
    }
    else if (pid > 0)
    {
        int i = 100000;
        while (i--)
        {
            (*data)++;
            printf("parent:%d\n", *data);
        }
        waitpid(pid, NULL, 0);//如果父进程先结束，调用wait等一下
    }
    else
    {
        perror("fork erorr");
    }
    shmdt(data);//父进程/子进程解映射
    shmctl(shmid, IPC_RMID, NULL);//销毁共享内存
    exit(0);
}
/*
    打印结果：child有时候能抢到，有时候抢不到
    有bug
*/